package com.lxyk.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lxyk.pojo.Customer;
import com.lxyk.pojo.History;
import com.lxyk.pojo.MainMenu;
import com.lxyk.pojo.Worker;
import com.lxyk.service.CustomerService;
import com.lxyk.service.HistoryService;
import com.lxyk.service.WorkerService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.cache.CacheProperties;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@Controller
@RequestMapping("/history")
@Slf4j
public class HistoryController {
    @Autowired
    private HistoryService historyService;
    @Autowired
    private CustomerService customerService;
    @Autowired
    private WorkerService workerService;
    @Autowired
    private RedisTemplate redisTemplate;


    @RequestMapping("/listHis")//如果是多条件放到map里就用@RequestParam
    public String listHistory(Model model, @RequestParam Map<String,Object>map,
                              @RequestParam(required = false,defaultValue = "1",value = "pageNum")Integer pageNum,
                              @RequestParam(defaultValue = "10",value = "pageSize")Integer pageSize){

        if (pageNum <= 0 || pageNum.equals("") || pageNum == null){
            pageNum = 1;
        }
        if (pageSize <= 0 || pageSize.equals("") || pageSize == null){
            pageSize = 10;
        }
        PageHelper.startPage(pageNum,pageSize);
        PageInfo<History> pageInfo = historyService.listHistory(map, pageNum, pageSize);
        model.addAttribute("pageInfo",pageInfo);
        return "historyList";
    }



    @RequestMapping("/preSaveHis")
    public String preSaveHis(Model model){
        List<Customer> custList = customerService.listCustomer();
        List<Worker> workerList = workerService.queryWorker();
        model.addAttribute("custList",custList);
        model.addAttribute("workerList",workerList);
        return "historySave";
    }

    @PostMapping("/saveHis")
    public String saveHistory(Integer workerId,Integer custId,History history){
        Worker worker = new Worker();
        worker.setWid(workerId);

        Customer cust = new Customer();
        cust.setCid(custId);

        history.setWorker(worker);
        history.setCustomer(cust);

        historyService.saveHistory(history);

        //清空redis 因为当我们redis有数据时就会走redis 但是当我们添加了送水工 就要重新排 就必须访问数据库 清空后就会访问数据库
        redisTemplate.delete("mainMenu");
        //再次查询数据库 设置新的redis
        List<MainMenu>mainMenu = new ArrayList<>();
        List<MainMenu>list = new ArrayList<>();
        Map<Integer,Integer>map=new HashMap<>();
        //送水工的送水总数量
        historyService.queryHistory().forEach(h ->{//h 是自定义的
                //在history表中一个送水工可能有多次送水记录 要把它们加起来
            map.put(h.getWorkerId(),map.getOrDefault(h.getWorkerId(),0)+h.getSendWaterCount());
        });

        //送水工人
        workerService.queryWorker().forEach(w ->{
            MainMenu main=new MainMenu();
            main.setWorkerName(w.getWorkerName());
            Integer count = map.get(w.getWid());//送水数量
            main.setSendWaterCount(count==null?0:count);
            list.add(main);
        });

        //排序
        Collections.sort(list,(o1, o2)->{
            if (o1.getSendWaterCount()>o2.getSendWaterCount()){
                return 1;
            }else if (o1.getSendWaterCount()<o2.getSendWaterCount()){
                return -1;
            }else {
                return 0;
            }
        });

        //把list数据添加到redis的集合 mainMenu1
        if (list.size()<12){
            mainMenu.addAll(list);//数量小于12 直接全部输出即可
        }
        for (int i = list.size()-12; i < list.size(); i++) {
            mainMenu.add(list.get(i));//如果数量大于12 则把前12条数据赋给新的list集合再输出这12条数据
        }

        //redis没有数据时 把数据库查询到的数据设置到redis中 下次直接从redis取数据即可
        redisTemplate.opsForList().leftPushAll("mainMenu",mainMenu);
        return "redirect:/history/listHis";//千万不要写成两个斜杠 否则访问的地址为//history/listHis 前边的local:8088/都没了 访问不到

    }

    @RequestMapping("/preUpdateHis/{hid}")
    public String preUpdateHis(@PathVariable("hid") Integer hid,Model model){
        List<Customer> custList = customerService.listCustomer();
        List<Worker> workerList = workerService.queryWorker();
        History history = historyService.getHistoryById(hid);
        model.addAttribute("custList",custList);
        model.addAttribute("workerList",workerList);
        model.addAttribute("history",history);
        return "historyUpdate";
    }
    @PostMapping("/updateHis")
    public String updateHis(Integer workerId,Integer custId,History history){//和新增里的一样 只是最后调的方法不一样
        Worker worker = new Worker();
        worker.setWid(workerId);

        Customer cust = new Customer();
        cust.setCid(custId);

        history.setWorker(worker);
        history.setCustomer(cust);
        historyService.updateHistory(history);
        return "redirect:/history/listHis";
    }

    @PostMapping("/batchDeleteHistory")
    @ResponseBody
    public String batchDeleteHistory(String idList){
        int rows = historyService.batchDeleteHistory(idList);
        if (rows>0){
            return "OK";
        }else {
            return "error";
        }
    }

}
